package com.pxl.springbootinit.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pxl.springbootinit.common.BaseResponse;
import com.pxl.springbootinit.common.ErrorCode;
import com.pxl.springbootinit.common.ResultUtils;
import com.pxl.springbootinit.exception.BusinessException;
import com.pxl.springbootinit.model.dto.user.UserFrom;
import com.pxl.springbootinit.model.dto.user.UserLoginRequest;
import com.pxl.springbootinit.model.dto.user.UserRegisterRequest;
import com.pxl.springbootinit.model.entity.User;
import com.pxl.springbootinit.model.enums.AvailableStatusEnum;
import com.pxl.springbootinit.model.vo.LoginUserVO;
import com.pxl.springbootinit.model.vo.UserVO;
import com.pxl.springbootinit.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 用户接口
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private PasswordEncoder passwordEncoder;

    // region 登录相关

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            return null;
        }
        long result = userService.userRegister(userAccount, userPassword, checkPassword);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        LoginUserVO loginUserVO = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(loginUserVO);
    }

    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        boolean logout = userService.userLogout(request);
        return ResultUtils.success(logout);
    }

    // endregion

    // region 用户管理相关


    /**
     * 获取单个用户详情
     */
    @GetMapping("/detail/{id}")
    public BaseResponse<UserVO> getUserById(@PathVariable("id") Long id) {
        if (id == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserVO user = userService.getUserById(id);
        return ResultUtils.success(user);
    }

    /**
     * 更新用户信息
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateUser(@RequestBody UserFrom userFrom) {
        if (userFrom == null || userFrom.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean updated = userService.updateUser(userFrom);
        return ResultUtils.success(updated);
    }

    /**
     * 删除用户
     */
    @PostMapping("/delete/{id}")
    public BaseResponse<Boolean> deleteUser(@PathVariable("id") Long id) {
        if (id == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean deleted = userService.deleteUser(id);
        return ResultUtils.success(deleted);
    }

    // endregion

    // region 管理员操作

    @PostMapping("/admin/add")
    public BaseResponse<Boolean> addUser(@RequestBody UserFrom userFrom) {
        if (userFrom == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        String encode = passwordEncoder.encode("12345678");
        BeanUtils.copyProperties(userFrom, user);
        user.setPassword(encode);
        boolean added = userService.save(user);
        return ResultUtils.success(added);
    }

    @PostMapping("/admin/pass/{id}")
    public BaseResponse<Boolean> passExamine(@PathVariable("id") Long id) {
        if (id == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(id);
        if (user == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户不存在");
        }
        user.setStatus(AvailableStatusEnum.ACTIVE.getValue());
        boolean updated = userService.updateById(user);
        return ResultUtils.success(updated);
    }

    @PostMapping("/admin/reject/{id}")
    public BaseResponse<Boolean> rejectExamine(@PathVariable("id") Long id) {
        if (id == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(id);
        if (user == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户不存在");
        }
        user.setStatus(AvailableStatusEnum.INACTIVE.getValue());
        boolean updated = userService.updateById(user);
        return ResultUtils.success(updated);
    }

    /**
     * 根据身份证查询所有用户信息
     */
    @GetMapping("/admin/list")
    public BaseResponse<List<UserVO>> getUserListByIdCard(UserFrom userFrom) {
        return ResultUtils.success(userService.getUserListByIdCard(userFrom));
    }

    /**
     * 获取所有用户（分页查询）
     */
    @GetMapping("/admin/page")
    public BaseResponse<Page<UserVO>> getUserList(UserFrom userFrom) {
        Page<UserVO> userPage = userService.getUserList(userFrom);
        return ResultUtils.success(userPage);
    }

    @GetMapping("/admin/examine/page")
    public BaseResponse<Page<UserVO>> getUserExamine(UserFrom userFrom) {
        Page<UserVO> userPage = userService.getUserExamine(userFrom);
        return ResultUtils.success(userPage);
    }

    /**
     * 返回系统总用户数量
     * @return
     */
    @GetMapping("/admin/count")
    public BaseResponse<Long> getUserCount() {
        Long count = userService.count();
        return ResultUtils.success(count);
    }

    /**
     * 获取今日活跃用户数量
     * @return
     */
    @GetMapping("/admin/today/active")
    public BaseResponse<Long> getTodayActiveCount() {
        return ResultUtils.success(userService.getTodayActiveCount());
    }
    // endregion
}
